'''
Author        zzx
Date          2024-07-22 16:43:02
LastEditTime  2024-11-14 15:10:30
LastEditors   zzx
Description   功能描述
'''
# -*- encoding: utf-8 -*-


import ast
from datetime import datetime
from app.modules.web.home import blueprint
from flask import render_template, request,current_app, session,url_for,redirect
from app.extensions.sqlalchemy import db
from app.modules.web.authentication.models import ServersInfo
from flask_login import login_required
from jinja2 import TemplateNotFound
from app.extensions.utils.apiClient import callApi


@blueprint.route('/index')
@login_required
def index():
    user_token = session['user_token']
    if user_token:
        # 调用 API 获取用户信息或其他数据
        res = callApi('/users', user_token, method='GET',params={'page': 1, 'size': 10})
        if res.get("error_code") == 0:
            return render_template('home/index.html', segment='index')
    return redirect(url_for('authentication_blueprint.login'))



@blueprint.route('/<template>')
@login_required
def route_template(template):

    try:

        if not template.endswith('.html'):
            template += '.html'

        # Detect the current page
        segment = get_segment(request)

        # Serve the file (if exists) from app/templates/home/FILE.html
        if segment == 'tables.html':
            queryset = ServersInfo.query.filter().order_by(ServersInfo.id.desc())

            queryset = queryset.filter(ServersInfo.delete_time == current_app.config.get('DEFAULT_DELETE_TIME'))
            data = queryset.all()
            return render_template("home/" + template, segment=segment, data=data) 
        return render_template("home/" + template, segment=segment)

    except TemplateNotFound:
        return render_template('home/page-404.html'), 404

    except:
        return render_template('home/page-500.html'), 500


# Helper - Extract current page name from request
def get_segment(request):

    try:

        segment = request.path.split('/')[-1]
        if segment == '':
            segment = 'index'

        return segment

    except:
        return None


# 显示编辑页面
@blueprint.route('/edit/<int:item_id>')
def edit_item(item_id):
    item = ServersInfo.query.get_or_404(item_id)  # 获取 item
    return render_template('home/edit_item.html', item=item)

# 处理表单提交并更新数据库
@blueprint.route('/update/<int:item_id>', methods=['POST'])
def update_item(item_id):
    item =ServersInfo.query.get_or_404(item_id)
    item.name= request.form['name']
    item.ip = request.form['ip']
    item.servers_id = request.form['servers_id']
    db.session.commit()  # 提交更改
    queryset = ServersInfo.query.filter().order_by(ServersInfo.id.desc())
    queryset = queryset.filter(ServersInfo.delete_time == current_app.config.get('DEFAULT_DELETE_TIME'))
    data = queryset.all()
    return render_template('/home/tables.html',data=data)  # 跳转回原页面

@blueprint.route('/delete/<int:item_id>', methods=['POST'])
def delete_item(item_id):
    # item = ServersInfo.query.get_or_404(item_id)
    ids = [item_id]
    ServersInfo.query.filter(ServersInfo.id.in_(ids)).update({"delete_time": datetime.now()})
    db.session.commit()  # 提交更改
    queryset = ServersInfo.query.filter().order_by(ServersInfo.id.desc())
    queryset = queryset.filter(ServersInfo.delete_time == current_app.config.get('DEFAULT_DELETE_TIME'))
    data = queryset.all()
    return render_template('/home/tables.html',data=data)  # 跳转回原页面

@blueprint.route('/add', methods=['GET', 'POST'])
def add_item():
    # item = ServersInfo.query.get_or_404(item_id)
    if request.method == 'POST':
        form_data = request.form
        form_data = dict(form_data)
        new_item = ServersInfo(**form_data)  # 创建新项目
        db.session.add(new_item)  # 添加到会话
        db.session.commit()  # 提交更改
        queryset = ServersInfo.query.filter().order_by(ServersInfo.id.desc())
        queryset = queryset.filter(ServersInfo.delete_time == current_app.config.get('DEFAULT_DELETE_TIME'))
        data = queryset.all()
        return render_template('/home/tables.html',data=data)  # 跳转回原页面
        # return redirect(url_for('home_blueprint.tables'))  # 跳转回原页面
    return render_template('/home/add_item.html')  # 显示添加页面